// JwtUtil.java
package com.guqin.interview.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;

public class JwtUtil {
    private static final String SECRET_KEY = "guqin_jwt_secret_key";
    private static final long EXPIRATION_TIME = 2 * 60 * 60 * 1000; // 2 hours

    // 使用更安全的方式初始化密钥
    private static final Key KEY = Keys.hmacShaKeyFor(
            DigestUtils.md5DigestAsHex(SECRET_KEY.getBytes(StandardCharsets.UTF_8))
                    .getBytes(StandardCharsets.UTF_8));

    public static String generateToken(Long userId) {
        return Jwts.builder()
                .setSubject(String.valueOf(userId))
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(KEY, SignatureAlgorithm.HS256)
                .compact();
    }

    public static Long getLoginUserId(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");

        String token = "";
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
        }
        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(KEY)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
            return Long.valueOf(claims.getSubject());
        } catch (Exception e) {
            // Token 无效或过期
            return null;
        }
    }

    public static String validateToken(String token) {
        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(KEY)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
            return claims.getSubject();
        } catch (JwtException | IllegalArgumentException e) {
            return null;
        }
    }
} 
